package com.ruoyi.integration.service;

import com.ruoyi.integration.service.token.TokenManager;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;

@RequiredArgsConstructor
public abstract class BaseIoTDataService {

    private final WebClient webClient;

    private final TokenManager tokenManager;

    private final static Logger log = LoggerFactory.getLogger(BaseIoTDataService.class);

    protected String getAccessToken(String deviceType) throws ExecutionException {
        try {
            return tokenManager.getToken(deviceType);
        } catch (Exception e) {
            log.warn("Token 获取失败，尝试刷新: {}", deviceType);
            tokenManager.refreshToken(deviceType);
            return tokenManager.getToken(deviceType);
        }
    }

    // 特定物联网数据请求返回: 不同服务器厂商提供的访问路径和方法不同，无法简单服用
    public <T> T doGet(String url, Class<T> clazz,
                       Map<String, String> headers) {
        return webClient.get()
                .uri(url)
                .headers(httpHeaders -> httpHeaders.setAll(headers))
                .retrieve()
                .bodyToMono(clazz)
                .block();
    }

}
